import jwt
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponseForbidden
import redis
import datetime

r = redis.Redis(host='localhost', port=6379, db=1)


class TokenVerificationMiddleware(MiddlewareMixin):
    def process_request(self, request):
        white_list = ['/send/', '/login/', '/logout/', '/ding/', '/back/',
                      '/callback/', '/qiniu/', '/baidu/', '/uploads/1.jpg/',
                      '/user/', '/a/', '/home/', '/cate/', '/uploads/4.jpg/',
                      '/uploads/2.jpg/']
        if request.path in white_list:
            return None
        token = request.headers.get('Authorization', '').replace('Bearer ', '')
        if not token:
            return HttpResponseForbidden('缺少token')
        try:
            payload = jwt.decode(token,'secret_key', algorithms=['HS256'])
            exptime = payload.get('exptime')
            if exptime and datetime.fromisoformat(exptime) < datetime.now():
                return HttpResponseForbidden('token已过期')
            if r.get(token):
                return HttpResponseForbidden('用户已退出')
        except jwt.ExpiredSignatureError:
            return HttpResponseForbidden('token已过期')
        except jwt.DecodeError:
            return HttpResponseForbidden('token无效')
        return None


